<template>
    <el-form :inline="true">
        <el-form-item label="关键字">
            <el-input v-model="searchRequest.keyword" placeholder="请输入查询关键字" autocomplete="off" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSearch" v-permission="'dict:query'"> 筛选 </el-button>
            <el-button type="info" @click="onReset" v-permission="'dict:query'"> 重置 </el-button>
            <el-divider direction="vertical" />
            <el-button type="success" @click="onAdd" v-permission="'dict:add'"> 添加主字典 </el-button>
            <el-button type="success" @click="onAddChild" v-permission="'dict:add'"> 添加字典明细 </el-button>
        </el-form-item>
    </el-form>
    <el-table :data="tableData" row-key="dictId" highlight-current-row
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @current-change="onSelectedChanged">
        <el-table-column prop="code" label="字典代码" width="200" />
        <el-table-column prop="name" label="字典名称" width="200" />
        <el-table-column prop="bak" label="备注" width="*" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
                <el-button link type="primary" @click="onDelete(scope.row)"
                    v-if="scope.row.hasChildren === false && hasPermission('dict:delete')">删除</el-button>
                <el-button link type="primary" @click="onEdit(scope.row)" v-permission="'dict:edit'">修改</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px" @close="dialogVisible = false">
        <el-form label-width="auto" ref="dictDataRef" :model="dictData" :rules="rules">
            <el-form-item v-if="isChild === true" label="主字典Id">
                <el-input v-model="dictData.parentName" readonly />
            </el-form-item>
            <el-form-item label="字典代码" prop="code">
                <el-input v-model="dictData.code" placeholder="请输入字典代码(不超过20个字符)" />
            </el-form-item>
            <el-form-item label="字典名称" prop="name">
                <el-input v-model="dictData.name" placeholder="请输入字典名称(不超过20个字符)" />
            </el-form-item>
            <el-form-item label="备注" prop="bak">
                <el-input v-model="dictData.bak" type="textarea" placeholder="请输入备注(不超过200个字符)" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSave(dictDataRef)"> 确定 </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import api from '@/apis/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DialogType, StorageKey } from '@/constant'
import appStorage from '@/stores/storage'

function hasPermission(permission) {
    let permissions = appStorage.getSession(StorageKey.PERMISSION_OPERATOR);
    let result = permissions.find(item => item.permissionCode == permission)
    return result == null ? false : true
}
//筛选
const searchRequest = reactive({
    keyword: null,
})
//表数据
const currentRow = ref({})//当前选中字典
const tableData = ref([])
//表单数据
const dictDataRef = ref()
const dictData = reactive({
    dictId: null,
    code: null,
    name: null,
    bak: null,
    parentId: null,//添加二级时需要用到
    parentName: null,//添加二级时需要显示
})
const rules = reactive({
    code: [{ required: true, message: "请输入字典代码", trigger: "blur" }, { max: 20, message: "字典代码不超过20个字符", trigger: "blur" }],
    name: [{ required: true, message: "请输入字典名称", trigger: "blur" }, { max: 20, message: "字典名称不超过20个字符", trigger: "blur" }],
    bak: [{ max: 200, message: "备注不超过200个字符", trigger: "blur" }]
});
//弹窗
const dialogTitle = ref('添加字典')
const dialogVisible = ref(false)
const dialogFlag = ref(DialogType.ADD)//dialog模式
const isChild = ref(false)
onMounted(async () => {
    try {
        loadTable()
    } catch (error) {
        console.error('数据加载失败:', error)
    }
})
function clearData() {
    dictData.dictId = null
    dictData.code = null
    dictData.name = null
    dictData.bak = null
    dictData.parentId = null
    dictData.parentName = null
}
//加载表数据
async function loadTable() {
    api.dict.getTree(searchRequest.keyword, resp => {
        tableData.value = resp.data
    }, null)
    currentRow.value = null//清空当前选中记录
}
//筛选
async function onSearch() {
    loadTable()
}
//重置
async function onReset() {
    searchRequest.keyword = null
    loadTable()
}
//当前记录
function onSelectedChanged(row) {
    currentRow.value = row
}
//创建一级字典
function onAdd() {
    clearData()
    dialogTitle.value = '添加主字典'
    dialogFlag.value = DialogType.ADD
    isChild.value = false
    dialogVisible.value = true
}
//创建二级字典
function onAddChild() {
    clearData()
    dialogTitle.value = '添加字典明细'
    // console.log(currentRow)
    if (currentRow.value == null || currentRow.value.parentId != null) {
        ElMessage('请选择主字典')
        return
    }
    dictData.parentId = currentRow.value.dictId
    dictData.parentName = currentRow.value.name
    dialogFlag.value = DialogType.ADD
    isChild.value = true
    dialogVisible.value = true
}
//保存字典
async function onSave(formEl) {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (dialogFlag.value == DialogType.ADD) {
                if (isChild.value) {
                    //添加二级
                    api.dict.addChild({
                        parentId: dictData.parentId,
                        code: dictData.code,
                        name: dictData.name,
                        bak: dictData.bak
                    }, resp => {
                        onReset()
                        ElMessage('添加成功')
                        dialogVisible.value = false
                    }, null)
                }
                else {
                    //添加一级
                    api.dict.addFirst({
                        code: dictData.code,
                        name: dictData.name,
                        bak: dictData.bak
                    }, resp => {
                        onReset()
                        ElMessage('添加成功')
                        dialogVisible.value = false
                    }, null)
                }

            }
            else if (dialogFlag.value == DialogType.EDIT) {
                api.dict.edit({
                    dictId: dictData.dictId,
                    code: dictData.code,
                    name: dictData.name,
                    bak: dictData.bak
                }, resp => {
                    onReset()
                    dialogVisible.value = false
                }, null)

            }

        }
    })
}
//修改字典
function onEdit(row) {
    clearData()
    dialogTitle.value = '修改字典信息'
    dialogFlag.value = DialogType.EDIT
    //修改时不需要修改上级，不需要显示上级字典
    isChild.value = false
    dialogVisible.value = true

    dictData.dictId = row.dictId
    dictData.code = row.code
    dictData.name = row.name
    dictData.bak = row.bak
}
//删除
function onDelete(row) {
    // console.log(row)
    ElMessageBox.confirm('确定删除?', '确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        .then(() => {
            api.dict.delete(row.dictId, resp => {
                onReset()
            }, null)
        }).catch(() => {

        })
}
</script>